// index/pages/dailyPracticeRankingList/dailyPracticeRankingList.js
const storageUtil = require('../../../utils/storageUtil');

Page({
  data: {
    hasRecords: true, // 控制有无记录的显示状态
    filterOptions: [
      { id: 'today', name: '本日排行榜' },
      { id: 'yesterday', name: '昨日排行榜' }
    ],
    currentFilter: 'today',
    rankingList: [],
    loading: false,
    practiceDaysLoading: false, // 练习天数加载状态
    baseUrl: 'http://localhost:8080'
  },

  onLoad(options) {
    console.log('排行榜页面加载', options);
    
    // 设置页面配置，优化滚动体验
    wx.setNavigationBarTitle({
      title: '一日一练排行榜'
    });
    
    this.loadRankingList();
  },

  /**
   * 加载排行榜数据
   */
  loadRankingList() {
    this.setData({ loading: true });
    
    // 根据筛选条件确定日期
    let practiceDate;
    if (this.data.currentFilter === 'today') {
      practiceDate = new Date().toISOString().split('T')[0]; // 今天的日期 YYYY-MM-DD
    } else {
      // 昨天的日期
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      practiceDate = yesterday.toISOString().split('T')[0];
    }
    
    console.log('加载排行榜，日期:', practiceDate, '筛选条件:', this.data.currentFilter);

    // 获取token
    const token = storageUtil.getToken();
    
    if (!token) {
      console.log('未获取到token，使用默认数据');
      this.setDefaultRankingData();
      this.setData({ loading: false });
      return;
    }

    // 调用后端接口获取排行榜数据
    wx.request({
      url: `${this.data.baseUrl}/hyg/practice/ranking`,
      method: 'GET',
      data: {
        pageNum: 1,
        pageSize: 50,
        practiceDate: practiceDate
      },
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        console.log('排行榜接口返回:', res);
        
        if (res.statusCode === 200 && res.data.code === 200) {
          const rankingData = res.data.rows || [];
          console.log('获取排行榜数据成功:', rankingData);
          
          if (rankingData.length > 0) {
            // 处理排行榜数据，添加排名
            const processedData = rankingData.map((item, index) => ({
              ...item,
              rank: index + 1,
              rankClass: this.getRankClass(index + 1),
              username: item.userName || `用户${item.userId}`,
              score: item.questionCount || 0, // 分数 = 刷题数量
              practiceDate: practiceDate
            }));
            
            this.setData({
              rankingList: processedData,
              hasRecords: true
            });
            
            // 获取每个用户的累计练习天数
            this.loadUserPracticeDays(processedData);
          } else {
            // 没有数据
            this.setData({
              rankingList: [],
              hasRecords: false
            });
            
            // 显示空状态提示
            wx.showToast({
              title: `${this.data.currentFilter === 'today' ? '今日' : '昨日'}暂无排行榜数据`,
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          console.error('获取排行榜数据失败:', res.data);
          // 显示错误提示
          wx.showToast({
            title: res.data?.msg || '获取排行榜失败',
            icon: 'none',
            duration: 2000
          });
          this.setDefaultRankingData();
        }
      },
      fail: (err) => {
        console.error('获取排行榜数据失败:', err);
        // 显示网络错误提示
        wx.showToast({
          title: '网络请求失败，请检查网络连接',
          icon: 'none',
          duration: 2000
        });
        this.setDefaultRankingData();
      },
      complete: () => {
        this.setData({ loading: false });
      }
    });
  },

  /**
   * 获取用户累计练习天数
   */
  loadUserPracticeDays(rankingList) {
    const token = storageUtil.getToken();
    
    if (!token) {
      console.log('未获取到token，无法获取练习天数');
      return;
    }
    
    this.setData({ practiceDaysLoading: true });
    
    rankingList.forEach((item, index) => {
      wx.request({
        url: `${this.data.baseUrl}/hyg/practice/user/${item.userId}/totalDays`,
        method: 'GET',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200) {
            const totalDays = res.data.data || 1;
            console.log(`用户${item.userId}累计练习天数:`, totalDays);
            
            // 更新对应项的数据
            const updatedList = [...this.data.rankingList];
            if (updatedList[index]) {
              updatedList[index].practiceDays = totalDays;
              this.setData({ rankingList: updatedList });
            }
          } else {
            console.error(`获取用户${item.userId}练习天数失败:`, res.data);
          }
        },
        fail: (err) => {
          console.error(`获取用户${item.userId}练习天数失败:`, err);
        },
        complete: () => {
          // 检查是否所有请求都完成
          if (index === rankingList.length - 1) {
            this.setData({ practiceDaysLoading: false });
          }
        }
      });
    });
  },

  /**
   * 设置默认排行榜数据（当接口失败时使用）
   */
  setDefaultRankingData() {
    const defaultData = [
      {
        id: 1,
        userId: 1001,
        username: '学霸小王',
        avatar: '/images/default-avatar.jpg',
        score: 95,
        practiceDays: 30,
        rank: 1,
        rankClass: 'rank-1'
      },
      {
        id: 2,
        userId: 1002,
        username: '学习达人',
        avatar: '/images/default-avatar.jpg',
        score: 92,
        practiceDays: 28,
        rank: 2,
        rankClass: 'rank-2'
      },
      {
        id: 3,
        userId: 1003,
        username: '知识探索者',
        avatar: '/images/default-avatar.jpg',
        score: 89,
        practiceDays: 25,
        rank: 3,
        rankClass: 'rank-3'
      },
      {
        id: 4,
        userId: 1004,
        username: '勤奋学习者',
        avatar: '/images/default-avatar.jpg',
        score: 87,
        practiceDays: 23,
        rank: 4,
        rankClass: 'rank-4'
      },
      {
        id: 5,
        userId: 1005,
        username: '知识追求者',
        avatar: '/images/default-avatar.jpg',
        score: 85,
        practiceDays: 22,
        rank: 5,
        rankClass: 'rank-5'
      }
    ];
    
    this.setData({
      rankingList: defaultData,
      hasRecords: true
    });
  },

  /**
   * 获取排名样式类
   */
  getRankClass(rank) {
    if (rank === 1) return 'rank-1';
    if (rank === 2) return 'rank-2';
    if (rank === 3) return 'rank-3';
    return 'rank-other';
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 筛选条件改变
  filterChange(e) {
    const filterIndex = e.detail.value;
    const selectedFilter = this.data.filterOptions[filterIndex];
    
    console.log('筛选条件改变:', selectedFilter);
    
    this.setData({
      currentFilter: selectedFilter.id
    });
    
    // 重新加载排行榜数据
    this.loadRankingList();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadRankingList();
    wx.stopPullDownRefresh();
  }
});